<?php
namespace App\Http\Controllers\v1;

use Illuminate\Http\Request;
use Mockery\Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\RequestBackController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\CheckController;
/*
    统计接口
*/
class CountController extends Controller{
    /*
    收费总金额
    */
    public function CasePayCount($request){
        if(!CheckController::CheckUser($request)){
            return RequestBackController::Structure(205);
        }
        $pos=$request->all();
        if(!CheckController::CheckParameter($pos,['CaseId'])){//
            return RequestBackController::Structure(502);
        }else{
            //案件应收费总额
            $CasePay = DB::connection('mysql_other')->table('yl_case as c')->select('c.case_id as CaseId','c.case_pay_count as CasePayCount')->where('case_id',$pos['CaseId'])->first();
			if($CasePay){
            //今日到账金额
				$CaseDayPay = DB::connection('mysql_other')->table('yl_proceeds')->select('proceeds_id as ProceedsId','proceeds_count as ProceedsCount','proceeds_creater_id as ProceedsCreaterId','proceeds_created_time as ProceedsCreatedTime','case_id as CaseId','proceeds_results_id as ProceedsResultsId','proceeds_end_time as ProceedsEndTime','proceeds_end as ProceedsEnd')->where('case_id',$pos['CaseId'])->get()
					 ->map(function ($val){
										$val = (array)$val;
										return $val;
										})
										->keyBy(function($item)
										{
											return $item['ProceedsId'];
										})->toArray();
				if($CaseDayPay){
					$YetPay = 0 ;//已经收款到账金额
					$DayPayCount = 0;//今日收款到账金额
					foreach ($CaseDayPay as $k => $v) {
						if(date("Y-m-d",$v['ProceedsEndTime']) ==date("Y-m-d",time()) && $v['ProceedsEnd'] == 1){
							$DayPayCount += $v['ProceedsCount'];
						}else{
							$DayPayCount = 0;
						}
						if($v['ProceedsEnd'] == 1){
							$YetPay += $v['ProceedsCount'];
						}
					}
					//案件总金额
					$CaseDayPay['CasePayCount'] =$CasePay->CasePayCount;
					//已收款金额 是否 == 已开票金额？
					$CaseDayPay['YetPay'] = $YetPay;
					//今日到账金额
					$CaseDayPay['DayPayCount'] = $DayPayCount;
					//剩余应收金额
					$RemainPay = $CasePay->CasePayCount - $YetPay;
					$CaseDayPay['RemainPay'] = $RemainPay;
					return RequestBackController::Structure(501,$CaseDayPay);
				}else{
					return RequestBackController::Structure(504);
				}
			}else{
				return RequestBackController::Structure(505);
			}
            

        }



    }

   
}